package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import com.zhijian.medical.dao.local.PersonMapper;
import com.zhijian.medical.entity.dto.FzImportDto;
import com.zhijian.medical.entity.dto.PersonImportDto;
import com.zhijian.medical.entity.po.*;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.*;
import com.zhijian.medical.enums.*;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 人员业务处理层
 *
 * @author HCG
 * @date 2022-01-01 15:41:25
 * @version: 1.0
 */
@Slf4j
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper mapper;

    @Autowired
    private OfficeGroupService officeGroupService;

    @Autowired
    private PersonRoleService personRoleService;

    @Autowired
    private PersonDetailService personDetailService;

    @Autowired
    private PersonExperienceService personExperienceService;

    /**
     * 默认登录密码
     */
    @Value("${default.password}")
    private String defaultPassword;

    @Autowired
    private AssessmentService assessmentService;

    @Autowired
    private StudyClassService studyClassService;

    @Autowired
    private FileService fileService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PersonGroupService personGroupService;

    @Override
    public Person selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public Person selectByPhone(String phone) {
        return mapper.selectByPhone(phone);
    }

    @Override
    public PersonVo selectVoById(Long id) {
        PersonVo personVo = mapper.selectVoById(id);
        if (Objects.nonNull(personVo)) {
            //角色id数组
            List<Long> roleIds = personRoleService.selectRolesByPersonId(id);
            personVo.setRoleIds(roleIds);
        }
        return personVo;
    }

    @Override
    public PersonVo selectVoByName(String name) {
        return mapper.selectVoByName(name);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(Person person) {
        Integer count = this.count(PersonSearchVo.builder()
                .jobNumber(person.getJobNumber())
                .build());
        AssertUtil.check(count > 0, "此工号用户已存在");
        Date now = new Date();
        person.setCreateTime(now);
        person.setUpdateTime(now);
        //默认正常状态
        person.setStatus(PersonStatusEnum.NORMAL.getCode().byteValue());
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(StringUtils.isBlank(person.getPassword())
                ? defaultPassword : person.getPassword(), salt);
        person.setPassword(finalPwd);
        person.setSalt(salt);
        person.setJobNumber(person.getJobNumber().trim());
        person.setAvatar(person.getAvatar());
        return mapper.insert(person) > 0 ? person.getId() : 0L;
    }

    @Override
    public boolean update(Person person) {
        Date now = new Date();
        person.setUpdateTime(now);
        return mapper.updateByPrimaryKey(person) != 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean update(PersonSaveOrUpdateVo personSaveOrUpdateVo) {
        AssertUtil.check(personSaveOrUpdateVo.getType() == PersonTypeEnum.ZZYG.getCode().byteValue() && CollectionUtil.isEmpty(personSaveOrUpdateVo.getRoleIds()), "角色id列表不能为空");
        Long personId = personSaveOrUpdateVo.getId();
        Person person = this.selectById(personId);
        AssertUtil.notNull(person, "此用户不存在或者已被删除");
        if (StringUtils.isNotBlank(personSaveOrUpdateVo.getJobNumber())) {
            Integer count = this.count(PersonSearchVo.builder()
                    .jobNumber(personSaveOrUpdateVo.getJobNumber())
                    .notId(personId)
                    .build());
            AssertUtil.check(count > 0, "此工号用户已存在");
        } else {
            person.setJobNumber(personSaveOrUpdateVo.getPhone());
        }

        person.setName(personSaveOrUpdateVo.getName());
        person.setPhone(personSaveOrUpdateVo.getPhone());
        person.setJobNumber(personSaveOrUpdateVo.getJobNumber());
        person.setNote(personSaveOrUpdateVo.getNote());
        person.setEmail(personSaveOrUpdateVo.getEmail());
        person.setStatus(personSaveOrUpdateVo.getStatus());
//        person.setType(personSaveOrUpdateVo.getType());
        person.setYear(personSaveOrUpdateVo.getYear());
        person.setAvatar(personSaveOrUpdateVo.getAvatar());
        person.setSxSchool(personSaveOrUpdateVo.getSxSchool());
        person.setStuStatus(personSaveOrUpdateVo.getStuStatus());
        person.setFzCompany(personSaveOrUpdateVo.getFzCompany());
        person.setCode(personSaveOrUpdateVo.getCode());
        person.setCode2(personSaveOrUpdateVo.getCode2());
        person.setDw(personSaveOrUpdateVo.getDw());
        person.setVersion(personSaveOrUpdateVo.getVersion());
        person.setSaveTime(personSaveOrUpdateVo.getSaveTime());
        person.setZrr(personSaveOrUpdateVo.getZrr());
        person.setPublishDate(personSaveOrUpdateVo.getPublishDate());
        person.setExecuteDate(personSaveOrUpdateVo.getPublishDate());
        //类型
        Byte type = person.getType();
        if (type == PersonTypeEnum.GPS.getCode().byteValue()) {
            //规培生的规培时间，同步到备注字段里
            person.setNote(String.format("%s-%s", personSaveOrUpdateVo.getGpStartDate(), personSaveOrUpdateVo.getGpEndDate()));
        } else if (type == PersonTypeEnum.JXS.getCode().byteValue()) {
            //进修生
            person.setNote(String.format("%s-%s", personSaveOrUpdateVo.getJxStartDate(), personSaveOrUpdateVo.getJxEndDate()));
        } else if (type == PersonTypeEnum.YJS.getCode().byteValue()) {
            //研究生
            person.setNote(personSaveOrUpdateVo.getYear());
        }

        this.update(person);

        //修改详情表
        PersonDetail personDetail = new PersonDetail();
        BeanUtils.copyProperties(personSaveOrUpdateVo, personDetail);
        personDetail.setPersonId(personId);
        //研究成果（研究生阶段）列表
        List<YjsYjCgVo> yjsYjCgList = personSaveOrUpdateVo.getYjsYjCgList();
        if (CollectionUtil.isNotEmpty(yjsYjCgList)) {
            personDetail.setYjCg(JsonUtil.toString(yjsYjCgList));
        } else {
            personDetail.setYjCg(null);
        }
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(personId)
                .type(FileTypeEnum.FZ_PCR.getCode().byteValue())
                .build());
        fileService.insertBatch(personSaveOrUpdateVo.getFzPcrFilePathList(), FileTypeEnum.FZ_PCR.getCode().byteValue(), personId);
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(personId)
                .type(FileTypeEnum.VISIT.getCode().byteValue())
                .build());
        fileService.insertBatch(personSaveOrUpdateVo.getVisitFilePathList(), FileTypeEnum.VISIT.getCode().byteValue(), personId);
        if (personDetailService.count(PersonDetailSearchVo.builder()
                .personId(personId)
                .build()) > 0) {
            //如果已经查到有这个人的记录，就修改，反之直接新增
            personDetailService.updateByPersonId(personDetail);
        } else {
            personDetailService.insert(personDetail);
        }

        //删除经历表
        personExperienceService.deleteByPersonId(personId);
        if (!CollectionUtils.isEmpty(personSaveOrUpdateVo.getStudyExperiences())) {
            //保存学习经历
            personSaveOrUpdateVo.getStudyExperiences().forEach(s -> {
                PersonExperience personExperience = new PersonExperience();
                BeanUtils.copyProperties(s, personExperience);
                personExperience.setType(PersonExperienceEnum.STUDY.getCode().byteValue());
                personExperience.setPersonId(personId);
                personExperienceService.insert(personExperience);
            });
        }
        if (!CollectionUtils.isEmpty(personSaveOrUpdateVo.getWorkExperiences())) {
            //保存工作经历
            personSaveOrUpdateVo.getWorkExperiences().forEach(s -> {
                PersonExperience personExperience = new PersonExperience();
                BeanUtils.copyProperties(s, personExperience);
                personExperience.setType(PersonExperienceEnum.WORK.getCode().byteValue());
                personExperience.setPersonId(personId);
                personExperienceService.insert(personExperience);
            });
        }

//        if (personSaveOrUpdateVo.getType() == PersonTypeEnum.ZZYG.getCode().byteValue()) {
//            //删除角色-人员关系表
//            personRoleService.deleteByPersonId(personId);
//            List<Long> roleIds = personSaveOrUpdateVo.getRoleIds();
//            roleIds.forEach(roleId -> personRoleService.insert(PersonRole.builder()
//                    .personId(personId)
//                    .roleId(roleId)
//                    .build()));
//        }
        return true;
    }

    @Override
    public boolean updateByPrimaryKeySelective(Person record) {
        return mapper.updateByPrimaryKeySelective(record) > 0;
    }

    @Override
    public Integer count(PersonSearchVo personSearchVo) {
        return mapper.count(personSearchVo);
    }

    @Override
    public List<PersonVo> selectList(PersonSearchVo personSearchVo) {
        return mapper.selectList(personSearchVo);
    }

    @Override
    public Page<PersonVo> selectPage(PersonSearchVo personSearchVo) {
        if (Objects.nonNull(personSearchVo.getGroupId())) {
            personSearchVo.setGroupIds(officeGroupService.concatIdsByParentId(personSearchVo.getGroupId()));
            personSearchVo.setGroupId(null);
        }
        //先直接查总数
        int count = count(personSearchVo);
        //分页
        Page<PersonVo> page = new Page<>(true, count, personSearchVo.getPageNum(), personSearchVo.getPageSize());
        personSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<PersonVo> responseVos = this.selectList(personSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public Person selectByJobNumberAndPassword(String jobNumber, String password) {
        return mapper.selectByJobNumberAndPassword(jobNumber, password);
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public Long insert(PersonSaveOrUpdateVo personSaveOrUpdateVo) {
        AssertUtil.check(personSaveOrUpdateVo.getType() == PersonTypeEnum.ZZYG.getCode().byteValue() && Objects.isNull(personSaveOrUpdateVo.getGroupId()), "科室id不能为空");
//        AssertUtil.check(personSaveOrUpdateVo.getType() == PersonTypeEnum.ZZYG.getCode().byteValue() && CollectionUtil.isEmpty(personSaveOrUpdateVo.getRoleIds()), "角色id列表不能为空");

        if (StringUtils.isNotBlank(personSaveOrUpdateVo.getJobNumber())) {
            Integer count = this.count(PersonSearchVo.builder()
                    .jobNumber(personSaveOrUpdateVo.getJobNumber())
                    .build());
            AssertUtil.check(count > 0, "此工号用户已存在");
        } else {
            personSaveOrUpdateVo.setJobNumber(personSaveOrUpdateVo.getPhone());
        }

        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(StringUtils.isBlank(personSaveOrUpdateVo.getPassword())
                ? defaultPassword : personSaveOrUpdateVo.getPassword(), salt);
        Date now = new Date();
        Person person = Person.builder()
                .name(personSaveOrUpdateVo.getName())
                .phone(personSaveOrUpdateVo.getPhone())
                .jobNumber(personSaveOrUpdateVo.getJobNumber())
                .note(personSaveOrUpdateVo.getNote())
                .status(personSaveOrUpdateVo.getStatus())
                .password(finalPwd)
                .salt(salt)
                .email(personSaveOrUpdateVo.getEmail())
                .type(personSaveOrUpdateVo.getType())
                .avatar(personSaveOrUpdateVo.getAvatar())
                .year(personSaveOrUpdateVo.getYear())
                .sxSchool(personSaveOrUpdateVo.getSxSchool())
                .stuStatus(personSaveOrUpdateVo.getStuStatus())
                .stuStatusChild(personSaveOrUpdateVo.getStuStatusChild())
                .fzCompany(personSaveOrUpdateVo.getFzCompany())
                .fzGw(personSaveOrUpdateVo.getFzGw())
                .sxzh(personSaveOrUpdateVo.getSxzh())
                .exCompany(personSaveOrUpdateVo.getExCompany())
                .zwKs(personSaveOrUpdateVo.getZwKs())
                .visitTime(personSaveOrUpdateVo.getVisitTime())
                .createTime(now)
                .updateTime(now)
                .build();

        person.setCode(personSaveOrUpdateVo.getCode());
        person.setCode2(personSaveOrUpdateVo.getCode2());
        person.setDw(personSaveOrUpdateVo.getDw());
        person.setVersion(personSaveOrUpdateVo.getVersion());
        person.setSaveTime(personSaveOrUpdateVo.getSaveTime());
        person.setZrr(personSaveOrUpdateVo.getZrr());
        person.setPublishDate(personSaveOrUpdateVo.getPublishDate());
        person.setExecuteDate(personSaveOrUpdateVo.getPublishDate());
        Long personId = mapper.insert(person) > 0 ? person.getId() : 0L;
        AssertUtil.check(personId == 0, "保存失败");
        //保存详情表
        PersonDetail personDetail = new PersonDetail();
        BeanUtils.copyProperties(personSaveOrUpdateVo, personDetail);
        personDetail.setPersonId(personId);
        //研究成果（研究生阶段）列表
        List<YjsYjCgVo> yjsYjCgList = personSaveOrUpdateVo.getYjsYjCgList();
        if (CollectionUtil.isNotEmpty(yjsYjCgList)) {
            personDetail.setYjCg(JsonUtil.toString(yjsYjCgList));
        }
        //辅助人员PCR上岗证，文件地址数组
        fileService.insertBatch(personSaveOrUpdateVo.getFzPcrFilePathList(), FileTypeEnum.FZ_PCR.getCode().byteValue(), personId);
        personDetailService.insert(personDetail);
        if (!CollectionUtils.isEmpty(personSaveOrUpdateVo.getStudyExperiences())) {
            //保存学习经历
            personSaveOrUpdateVo.getStudyExperiences().forEach(s -> {
                PersonExperience personExperience = new PersonExperience();
                BeanUtils.copyProperties(s, personExperience);
                personExperience.setType(PersonExperienceEnum.STUDY.getCode().byteValue());
                personExperience.setPersonId(personId);
                personExperienceService.insert(personExperience);
            });
        }
        if (!CollectionUtils.isEmpty(personSaveOrUpdateVo.getWorkExperiences())) {
            //保存工作经历
            personSaveOrUpdateVo.getWorkExperiences().forEach(s -> {
                PersonExperience personExperience = new PersonExperience();
                BeanUtils.copyProperties(s, personExperience);
                personExperience.setType(PersonExperienceEnum.WORK.getCode().byteValue());
                personExperience.setPersonId(personId);
                personExperienceService.insert(personExperience);
            });
        }
        List<Long> roleIds = personSaveOrUpdateVo.getRoleIds();
        if (personSaveOrUpdateVo.getType() == PersonTypeEnum.GPS.getCode().byteValue()) {
            //规培升
            roleIds = RoleNewEnum.GPS.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.JXS.getCode().byteValue()) {
            //进修生
            roleIds = RoleNewEnum.JXS.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.YJS.getCode().byteValue()) {
            //研究生
            roleIds = RoleNewEnum.YJS.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.FZRY.getCode().byteValue()) {
            //辅助人员
            roleIds = RoleNewEnum.FZRY.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.ZXPXRY.getCode().byteValue()) {
            //专项辅助人员
            roleIds = RoleNewEnum.ZXPXRY.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.SXS.getCode().byteValue()) {
            //实习生
            roleIds = RoleNewEnum.SXS.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.LH.getCode().byteValue()) {
            //轮换
            roleIds = RoleNewEnum.LH.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.ZZYG.getCode().byteValue()) {
            //轮换
            roleIds = RoleNewEnum.ZG.getCodes();
        } else if (personSaveOrUpdateVo.getType() == PersonTypeEnum.OTHER.getCode().byteValue()) {
            //其他
            roleIds = RoleNewEnum.OTHER.getCodes();
        }
        roleIds.forEach(roleId -> personRoleService.insert(PersonRole.builder()
                .personId(personId)
                .roleId(roleId)
                .build()));
        if (Objects.nonNull(personSaveOrUpdateVo.getGroupId())) {
            //插入人员-组织关系表
            personGroupService.insert(PersonGroup.builder()
                    .personId(personId)
                    .groupId(personSaveOrUpdateVo.getGroupId())
                    .build());
        }
        return personId;
    }

    @Override
    public PersonVo selectVoByJobNumber(String jobNumber) {
        return mapper.selectVoByJobNumber(jobNumber);
    }

    @Override
    public List<PersonExamRecordVo> selectPersonExamRecordVoByUserId(Long userId) {
        return mapper.selectPersonExamRecordVoByUserId(userId);
    }

    @Override
    public PersonAllVo selectAllVoById(Long id) {
        PersonVo personVo = this.selectVoById(id);
        if (Objects.isNull(personVo)) {
            return null;
        }
        PersonAllVo personAllVo = new PersonAllVo();
        BeanUtils.copyProperties(personVo, personAllVo);
        PersonDetailVo personDetailVo = personDetailService.selectVoByPersonId(id);
        if (Objects.nonNull(personDetailVo)) {
            BeanUtils.copyProperties(personDetailVo, personAllVo);
            //研究成果（研究生阶段）列表
            String yjCg = personDetailVo.getYjCg();
            personAllVo.setYjsYjCgList(JsonUtil.toArray(yjCg, YjsYjCgVo.class));
        }
        //辅助人员PCR上岗证，文件地址数组
        List<FileVo> fileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.FZ_PCR.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(fileVos)) {
            personAllVo.setFzPcrFilePathList(fileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }
        //访问人员访问概况，文件地址数组
        List<FileVo> visitFileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.VISIT.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(visitFileVos)) {
            personAllVo.setVisitFilePathList(visitFileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }


        //学习经历
        List<PersonExperienceVo> studyPersonExperienceVos = personExperienceService.selectList(PersonExperienceSearchVo.builder()
                .personId(id)
                .type(PersonExperienceEnum.STUDY.getCode().byteValue())
                .build());
        personAllVo.setStudyExperiences(studyPersonExperienceVos);
        //工作经历
        List<PersonExperienceVo> workPersonExperienceVos = personExperienceService.selectList(PersonExperienceSearchVo.builder()
                .personId(id)
                .type(PersonExperienceEnum.WORK.getCode().byteValue())
                .build());
        personAllVo.setWorkExperiences(workPersonExperienceVos);
        return personAllVo;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public String registerTrainByAssessment(RegisterTrainByAssessmentVo registerTrainByAssessmentVo) {
        StudyClass studyClass = studyClassService.selectById(registerTrainByAssessmentVo.getAssessmentId());
        AssertUtil.notNull(studyClass, "此学习班不存在或者已被删除");

        Person person = this.selectByPhone(registerTrainByAssessmentVo.getPhone());
        if (Objects.nonNull(person)) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, String.format("此手机号已注册，请直接使用工号'%s'进行登录", person.getJobNumber()));
        }
        PersonSaveOrUpdateVo personSaveOrUpdateVo = new PersonSaveOrUpdateVo();
        BeanUtils.copyProperties(registerTrainByAssessmentVo, personSaveOrUpdateVo);
        //给他造个工号
        String jobNumber = String.format("%s%s", registerTrainByAssessmentVo.getPhone(), RandomUtil.randomString(4));
        personSaveOrUpdateVo.setJobNumber(jobNumber);
        //类型为 专项培训人员
        personSaveOrUpdateVo.setType(PersonTypeEnum.ZXPXRY.getCode().byteValue());
        //默认正常
        personSaveOrUpdateVo.setStatus(PersonStatusEnum.NORMAL.getCode().byteValue());
        //单位
        personSaveOrUpdateVo.setCompany(registerTrainByAssessmentVo.getCompany());
        //科室
        personSaveOrUpdateVo.setGroupName(registerTrainByAssessmentVo.getGroupName());
        //保存完人的用户ID
        Long personId = this.insert(personSaveOrUpdateVo);
        //如果
        Assessment assessment = assessmentService.selectByStudyClassId(studyClass.getId());

        String doPersonIds = studyClass.getDoPersonIds();
        List<Long> personIdList = Lists.newArrayList();
        //把做题人的用户ID塞进去
        if (StringUtils.isNotBlank(doPersonIds)) {
            personIdList = Arrays.stream(doPersonIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        }
        personIdList.add(personId);
        doPersonIds = StrUtil.join(",", personIdList);
        //修改
        studyClassService.updateByPrimaryKeySelective(StudyClass.builder()
                .id(studyClass.getId())
                .doPersonIds(doPersonIds)
                .build());
        if (Objects.nonNull(assessment)) {
            //修改
            assessmentService.updateByPrimaryKeySelective(Assessment.builder()
                    .id(assessment.getId())
                    .doPersonIds(doPersonIds)
                    .build());
        }
        return jobNumber;
    }

    @Override
    public boolean importExcel(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelReader reader = ExcelUtil.getReader(inputStream)
                .addHeaderAlias("工号", "jobNumber")
                .addHeaderAlias("姓名", "name")
                .addHeaderAlias("职称", "roleName")
                .addHeaderAlias("组", "groupName");
        List<PersonImportDto> personList = reader.readAll(PersonImportDto.class);
        AssertUtil.check(CollectionUtil.isEmpty(personList), "数据至少要有一行");
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(defaultPassword, salt);
        Date now = new Date();
        for (PersonImportDto person : personList) {
            Person person1 = new Person();
            person1.setName(person.getName());
            person1.setJobNumber(person.getJobNumber());
            //默认正常状态
            person1.setStatus(PersonStatusEnum.NORMAL.getCode().byteValue());
            person1.setPassword(finalPwd);
            person1.setSalt(salt);
            person1.setType((byte) 0);
            person1.setCreateTime(now);
            person1.setUpdateTime(now);
            try {
                RoleVo roleVo = roleService.selectVoByName(person.getRoleName());
                Long personId = mapper.insert(person1) > 0 ? person1.getId() : 0L;
                personRoleService.insert(PersonRole.builder()
                        .personId(personId)
                        .roleId(roleVo.getId())
                        .build());
                OfficeGroupVo officeGroupVo = officeGroupService.selectVoByName(person.getGroupName());
                personGroupService.insert(PersonGroup.builder()
                        .personId(personId)
                        .groupId(officeGroupVo.getId())
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    //    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean importFzExcel(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelReader reader = ExcelUtil.getReader(inputStream)
                .addHeaderAlias("公司", "company")
                .addHeaderAlias("姓名", "name")
                .addHeaderAlias("手机", "phone");
        List<FzImportDto> fzImportDtos = reader.readAll(FzImportDto.class);
        AssertUtil.check(CollectionUtil.isEmpty(fzImportDtos), "数据至少要有一行");
        String salt = EncryptUtil.salt();
        //密码加盐，形成最后真正的密码
        String finalPwd = EncryptUtil.password(defaultPassword, salt);
        Date now = new Date();
        for (FzImportDto fzImportDto : fzImportDtos) {
            Person person = new Person();
            person.setName(fzImportDto.getName());
            person.setJobNumber(fzImportDto.getPhone());
            person.setPhone(fzImportDto.getPhone());
            //默认正常状态
            person.setStatus(PersonStatusEnum.NORMAL.getCode().byteValue());
            person.setPassword(finalPwd);
            person.setSalt(salt);
            person.setType((byte) 4);
            person.setNote(fzImportDto.getCompany());
            person.setCreateTime(now);
            person.setUpdateTime(now);
            try {
                Long personId = mapper.insert(person) > 0 ? person.getId() : 0L;
                personRoleService.insert(PersonRole.builder()
                        .personId(personId)
                        .roleId(RoleNewEnum.FZRY.getCodes().get(0))
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public boolean updateSignPic(Long personId, String signPicFilePath) {
        Person person = this.selectById(personId);
        AssertUtil.notNull(person, "此用户不存在或者已被删除");
        person.setSignPic(signPicFilePath);
        return this.update(person);
    }

    @Override
    public String createNextCode(Byte type) {
        PersonTypeEnum personTypeEnum = PersonTypeEnum.getByCode(type.intValue());
        assert personTypeEnum != null;
        String maxCode = this.selectMaxCode(type);
        if (StringUtils.isBlank(maxCode)) {

            return String.format("%s-%s-1", personTypeEnum.getVersionCode(), DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")));
        }
        String[] maxCodeArray = maxCode.split("-");
        Integer i = Integer.valueOf(maxCodeArray[maxCodeArray.length - 1]);
        i++;
        return String.format("%s-%s-%s", personTypeEnum.getVersionCode(), DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")), i);
    }

    @Override
    public String selectMaxCode(Byte type) {
        return mapper.selectMaxCodeByDay(type, DateUtil.formatDate(new Date()));
    }

}